package cn.edu.tju.elm.repository;

import cn.edu.tju.elm.model.AiChatMessage;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Repository;

import java.util.List;
import java.util.Optional;

@Repository
public interface AiChatMessageRepository extends JpaRepository<AiChatMessage, Long> {

    List<AiChatMessage> findByUserIdAndSessionIdOrderByTimestampAsc(Long userId, String sessionId);

    Page<AiChatMessage> findByUserIdAndSessionIdOrderByTimestampDesc(Long userId, String sessionId, Pageable pageable);

    @Query("SELECT DISTINCT a.sessionId FROM AiChatMessage a WHERE a.userId = :userId ORDER BY a.timestamp DESC")
    List<String> findDistinctSessionIdsByUserId(Long userId);

    Optional<AiChatMessage> findTopByUserIdAndSessionIdOrderByTimestampDesc(Long userId, String sessionId);

    Long countByUserIdAndSessionId(Long userId, String sessionId);
}